package com.ftg.learn;

import com.alibaba.dashscope.aigc.completion.ChatCompletionChunk;
import com.alibaba.dashscope.aigc.completion.ChatCompletionParam;
import com.alibaba.dashscope.aigc.completion.ChatCompletions;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.Flowable;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author 布衣
 */
public class ChaiAi {

    public static void main(String[] args) throws NoApiKeyException, InputRequiredException {


        System.out.println("-============-");
        System.out.println("-============-");
        System.out.println("欢迎来到ChatGPT");
        System.out.println("-============-");
        System.out.println("-============-");

        Scanner s = new Scanner(System.in);



        Constants.apiKey="sk-510b917932744b3680b858b474fbd919";
        Constants.baseHttpApiUrl="https://dashscope.aliyuncs.com/compatible-mode/v1";

        ChatCompletions c = new ChatCompletions();

        List<Message> list = new ArrayList<>();
        Message sysMess = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是东北跳大神的，老翟头")
                .build();
        list.add(sysMess);

        while(true){
            System.out.println("请输入您要使用的操作，exit为退，想对话直接输入内容");
            String op = s.next();
            if(op.equals("exit")){
                break;
            }

            Message userMess = Message.builder()
                    .role(Role.USER.getValue())
                    .content(op)
                    .build();
            list.add(userMess);

            ChatCompletionParam param = ChatCompletionParam.builder()
                    .model("qwen-plus")
                    .messages(list)
                    .stream(true)
                    .build();

            StringBuilder sb = new StringBuilder();

            Flowable<ChatCompletionChunk> chatCompletionChunkFlowable = c.streamCall(param);
            chatCompletionChunkFlowable.blockingForEach(chatCompletionChunk -> {
                System.out.print(chatCompletionChunk.getChoices().get(0).getDelta().getContent());
                sb.append(chatCompletionChunk.getChoices().get(0).getDelta().getContent());
            });
            System.out.println();

            Message assistMess = Message.builder()
                    .role(Role.ASSISTANT.getValue())
                    .content(sb.toString())
                    .build();
            list.add(assistMess);

        }
    }

}
